package com.lvyou.ctrls.mgr;

import com.lvyou.entity.GoodsModel;
import com.lvyou.service.GoodsSrvImpl;
import com.lvyou.vo.GoodsVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

//商品
@Controller
@RequestMapping("/mgr/goods")
public class GoodsMgrCtrl {
    @Resource
    private GoodsSrvImpl srv;

    @RequestMapping("/query")
//    public ModelAndView query() {
    public ModelAndView list() {
        /*
        视图名
        传递给jsp的数据
         */
        ModelAndView mv = new ModelAndView();
        List<GoodsModel> list=srv.query();
        mv.setViewName("goodsList");
        mv.addObject("list",list);
        return mv;
    }
    @RequestMapping("/save")
    public ModelAndView save(MultipartFile file, GoodsVO gv, HttpServletRequest req) {
        //非空验证
        //对价格做校验，数字、上限、负数校验


        ModelAndView mv = new ModelAndView();

        if(!file.isEmpty()) {
            //动态创建保存上传文件的文件夹   : /upload
            String upload = req.getSession().getServletContext().getRealPath("/upload");
            File uploadFile = new File(upload);
            if (!uploadFile.exists()) {
                uploadFile.mkdirs();
            }
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //获取原图片后缀
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            String suffix = file.getOriginalFilename().substring(dotPos);

            File newFile = new File(uploadFile, uuid + suffix);
            //移动文件
            try {
                file.transferTo(newFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        int price=Integer.parseInt(gv.getPrice());

        GoodsModel gm=new GoodsModel();
        BeanUtils.copyProperties(gv,gm);
        gm.setPrice(price);

        srv.save(gm);
        mv.setViewName("redirect:/query");
        return mv;
    }

    @RequestMapping("/showById")
    public ModelAndView showById(String id){
//    public ModelAndView queryById(){
        return null;
    }

    @RequestMapping("/deleteById")
    public ModelAndView deleteById(String id){
        return null;
    }

    @RequestMapping("/updateById")
//    public ModelAndView modifyById(String id){
    public ModelAndView updateById(String id){

        return null;
    }
}
